package com.cusi.config;



import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    //ShiroFilterFactoryBean :3
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(@Qualifier("securityManager")DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean bean = new ShiroFilterFactoryBean();
        //设置安全管理器
        bean.setSecurityManager(defaultWebSecurityManager);

        //添加shiro的内置过滤器
        /*
            anon: 无需认证就可以访问；
            authc：必须认证了才能访问；
            user：必须拥有 记住我 功能才可以访问；
            perms：拥有对某个资源的权限才能访问；
            role：拥有某个角色才能访问；
         */

        //登录拦截
        Map<String, String> filterMap = new LinkedHashMap<>();

        //授权  必须是user用户，add权限
        filterMap.put("/index","anon");
        filterMap.put("/","anon");
        filterMap.put("/logout","logout");
        filterMap.put("/views/level1","perms[views:level1]");
        filterMap.put("/views/level2","perms[views:level2]");
        filterMap.put("/views/level3","perms[views:level3]");
        filterMap.put("/toLogin", "anon");
        filterMap.put("/**", "authc");

        bean.setLoginUrl("/login");
      //  bean.setSuccessUrl("/index");
        bean.setUnauthorizedUrl("/unAuth");

        bean.setFilterChainDefinitionMap(filterMap);
        return bean;
    }

    //DafaulDefaultWebSecurityManager :2
    @Bean(name="securityManager")
    public DefaultWebSecurityManager getDefaultWebSecurityManger(@Qualifier("userRealm") UserRealm userRealm){
        DefaultWebSecurityManager securityManager = new DefaultWebSecurityManager();
        securityManager.setRealm(userRealm);
        return securityManager;
    }

    //创建自定义的realm 对象 1
    @Bean
    public UserRealm userRealm(){
        return new UserRealm();
    }

    //整合thymeleaf 和 shiro
    @Bean
    public ShiroDialect getShiroDialect(){
        return  new ShiroDialect();
    }
}
